const RongIMLib = require('./@rongcloud/imlib-v4/index')
import {rongId} from '../config'
export const rongIM = {
  // 初始化融云sdk
  initRong(){
    const config = {appkey:rongId,connectionType:'comet'}
    return RongIMLib.init(config);
  },
  // 链接融云
	connectRong(im){
		let user = {token: wx.getStorageSync('userInfo').rc_token}
    im.connect(user).then((user) => {
      console.log('链接成功, 链接用户 id 为: ', user.id)
      wx.$rong_success = true
    }).catch((error) => {
      console.log('链接失败: ', error.code, error.msg)
      wx.$rong_success = (error.code == 34001 ? true :false)// 34001 链接还存在，仍然有效
      if(error.code == 31004){
        wx.reLaunch({
          url: '/pages/index/index'
        })
      }
    })
	},
  //加入聊天室
  join(roomid){
    wx.chatRoom = wx.im.ChatRoom.get({ // 实例化聊天室
      id: roomid
    })
    console.log(wx.chatRoom,'聊天室实例，加入')
    wx.chatRoom.join({
      count: -1 // 不拉取历史消息
    }).then(() => {
      console.log('加入聊天室成功')
    }).catch(()=>{
      console.log('加入聊天室失败')
    });
  },
  // 退出聊天室
  exitRoom(){
    return new Promise(resolve =>{
      if(typeof wx.chatRoom == 'object'){
        console.log(wx.chatRoom,'聊天室实例，退出')
        wx.chatRoom.quit().then(() => {
          console.log('退出聊天室成功');
          wx.chatRoom = undefined
          resolve()
        }).catch(()=>{
          console.log('退出聊天室失败')
          resolve()
        });
      }else {
        resolve()
      }
    })
  },
  // 融云链接断开
  breakConnect(){
    wx.im.disconnect().then(() => {
      console.log('断开链接成功')
    })
  },
  // 消息监听
  watchMessage($event,im){
    console.log(im,'消息监听开始')
    im.watch({
      conversation: (event) =>{
        let updatedConversationList = event.updatedConversationList; // 更新的会话列表
        // console.log('更新会话汇总:', updatedConversationList);
      },
      // 实时消息反馈
      message: (event) =>{
        let message = event.message;
        // console.log('收到新消息', message)
        const { messageType, content } = message
        switch (messageType) {
          case "CB:ROOM":
            $event.emit('cb_room',content)
            break;
          case "CB:MESSAGE":
              $event.emit('cb_message',content)
            break;
        
          default:
            break;
        }
      },
      // 融云链接状态
      status: function(event){
        let status = event.status;
        switch (status) {
          case RongIMLib.CONNECTION_STATUS.CONNECTED:
            console.log('链接成功');
            break;
          case RongIMLib.CONNECTION_STATUS.CONNECTING:
            console.log('正在连接中');
            break;
          case RongIMLib.CONNECTION_STATUS.DISCONNECTED:
            console.log('已主动断开连接');
            break;
          case RongIMLib.CONNECTION_STATUS.NETWORK_UNAVAILABLE:
            console.log('网络不可用'); // SDK 内部会自动进行重连
            break;
          case RongIMLib.CONNECTION_STATUS.SOCKET_ERROR:
            console.log('Socket 链接错误'); // SDK 内部会自动进行重连
            break;
          case RongIMLib.CONNECTION_STATUS.KICKED_OFFLINE_BY_OTHER_CLIENT:
            console.log('其他设备登录, 本端被踢'); // 己端被踢, 不可进行重连. 否则会造成多端循环互踢
            break;
          case RongIMLib.CONNECTION_STATUS.BLOCKED:
            console.log('链接断开, 用户已被封禁');
            break;
          default:
            console.log('链接状态变化为:', status);
            break;
        }
      }
    })
  },
}